package com.suyang.syt.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.dao.interfaces.OperateLogDao;
import com.suyang.syt.model.OperateLog;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.service.interfaces.OperateLogService;
import com.suyang.syt.util.EmptyUtil;

@Service
public class OperateLogServiceImpl implements OperateLogService {
	@Autowired
	private OperateLogDao operateLogDao;

	@Override
	public AjaxObj delete(String ids) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idss = ids.split(",");
			if (idss != null && idss.length > 0) {
				for (String id : idss) {
					operateLogDao.delete(Long.parseLong(id));
				}
				return new AjaxObj(1, "删除成功！");
			}
		} else {
			return new AjaxObj(0, "请选择要删除的记录！");
		}
		return new AjaxObj(0, "删除失败！");
	}

	@Override
	public PagerEasyUI<OperateLog> listByEasyUI(int page, int rows, String sort, String order, String isException, OperateLog operateLog, String createDate1, String createDate2) throws Exception {
		StringBuilder hql = new StringBuilder(" from OperateLog o where 1=1 ");
		if (EmptyUtil.isNotEmpty(createDate1)) {
			hql.append(" and o.createTime >= '").append(createDate1).append("' ");
		}
		if (EmptyUtil.isNotEmpty(createDate2)) {
			hql.append(" and o.createTime <= '").append(createDate2).append("' ");
		}
		if (operateLog != null && EmptyUtil.isNotEmpty(operateLog.getCreateName())) {
			hql.append(" and o.createName like '%").append(operateLog.getCreateName()).append("%' ");
		}
		if (operateLog != null && EmptyUtil.isNotEmpty(operateLog.getAction())) {
			hql.append(" and o.action like '%").append(operateLog.getAction()).append("%' ");
		}
		if (EmptyUtil.isNotEmpty(isException)) {
			hql.append(" and o.exception is not null ");
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by o.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}

		PagerEasyUI<OperateLog> easyUIPager = new PagerEasyUI<OperateLog>();
		// 2、获取用户easyUI数据
		List<OperateLog> operateLogs = operateLogDao.findByEasyUI(hql.toString(), page, rows);
		easyUIPager.setRows(operateLogs);
		easyUIPager.setTotal((Long) operateLogDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		return easyUIPager;
	}

	@Override
	public void add(OperateLog operateLog) {
		operateLogDao.add(operateLog);
	}
}